const QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
const log = require('../../log.js')
const {
  formatTime,
  changeTime
} = require('../../utils/util.js');
const {
  getTime,
  getAttence,
  upData, 
  getAttendPoster,
  getAllPoster
} = require('../../api/geData.js')
const {
  globalData
} = getApp()
let qqMapSdk;
Component({
  properties: {
    courseData: null
  },

  data: {
    nowTime: '11:38:19', // 当前时间
    millisecond: null,
    to: {},
    from: {},
    distance: null,
    userInfo: null,
    fieldAddress:'',
    showResultcourse:false,
    index: 0,
    posterBg: [],
    monthNum: '',
    posterData: {}
    // isShowEmpower:false
  },

  attached() {
    let that = this
    // 实例化QQ地图
    qqMapSdk = new QQMapWX({
      key: 'WX7BZ-5PI66-ZKGSD-ET5VF-ZC3RZ-TFBVB'
    })

    this.setData({
      userInfo:globalData.userInfo
    })
    // 获取服务器时间
    this.getNowTime.call(this)

    this.getTimeFn()
    
    this.getLocationFn()
    // let courseData = this.properties.courseData
    getAllPoster(2).then(res=>{
      log.error('getAllPoster', res)
      this.setData({
        posterBg: res.list
      })
      // getAttendPoster(courseData.id).then(res => {
      //   log.error('getAttendPoster',res)
      //   this.setData({
      //     monthNum:res.number,
      //     posterData:res.map
      //   })
      //   this.createPosterPic()
      // })
    })
  },

  methods: {
    // // 二次授权弹框
    // toggleEmpowerDialog(){
    //   this.setData({
    //     isShowEmpower: !this.data.isShowEmpower
    //   })
    // },
    // // 关闭
    // closeEmpower(){
    //   this.setData
    //   ({
    //       isShowEmpower: false
    //   })
    // },
    // 转化坐标函数
    reverseGeocoder(latitude, longitude, distance){
      let that = this

      that.setData({
        to: {
          latitude: latitude,
          longitude: longitude
        },
        distance: distance
      })

      // qqMapSdk.reverseGeocoder({
      //   location: {
      //     latitude: latitude,
      //     longitude: longitude
      //   },
      //   coord_type: 3,
      //   success: function (res) {
      //     var location = res.result.ad_info.location;
      //     that.setData({
      //       to: {
      //         latitude: location.lat,
      //         longitude: location.lng
      //       },
      //       distance: distance
      //     })
      //   }
      // })
    },
    getTimeFn(){
      let that = this
      getTime().then(res => {
        // res.currentTime = 1554080301000
        that.setData({
          millisecond: res.currentTime,
          nowTime: formatTime(res.currentTime, 3).split(' ')[1]
        })
      }).catch(err => {
        console.log(err)
      })
    },
    // 获取地理权限
    getLocationFn() {
      setTimeout(()=>{
        let that = this,
          courseData = that.properties.courseData,
          ne = courseData.ne && courseData.ne.split(',');
        clearTimeout(globalData.timer)
        // console.log('courseData.add')
        // console.log(courseData.add)
        // 已经打卡
        if (!courseData.showClockIn) return
        console.log(courseData)
        if(courseData.fieldAttend=='1'){
        }else{
          // 今天没有排课
          if (!courseData.add) return
          // this.reverseGeocoder(ne[1], ne[0], courseData.distance)
          this.setData({
            to: {
              latitude: ne[1],
              longitude: ne[0]
            },
            distance: courseData.distance
          })
        }


        wx.getSetting({
          success(res) {
            if (res.authSetting['scope.userLocation'] != true) { // 没有受权过
                wx.showModal({
                  title: '是否授权当前位置',
                  content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                  success(msg) {
                    if (msg.confirm) {
                      wx.getLocation({
                        type: 'gcj02',
                        success: function (res) {
                          let from = {
                            latitude: res.latitude,
                            longitude: res.longitude
                          }
                          that.setData({
                            from: from
                          })
                          wx.showLoading({
                            title: '正在获取数据',
                            mask: true
                          })
                          if (courseData.fieldAttend == '1') {
                            that.getFieldAttend.call(that)
                          } else {
                            that.getDistance.call(that)
                          }
                          wx.hideLoading()
                        }, fail(res) {
                          console.log(res)
                          wx.getSetting({
                            success: function (res) {
                              if (!res.authSetting['scope.userLocation']) {
                                wx.showModal({
                                  title: '',
                                  content: '请允许国科考勤获取您的定位',
                                  confirmText: '授权',
                                  success: function (res) {
                                    if (res.confirm) {
                                      that.openSettting()
                                    } else {
                                      console.log('get location fail');
                                    }
                                  }
                                })
                              } 
                              // else {
                              //   //用户已授权，但是获取地理位置失败，提示用户去系统设置中打开定位            
                              //   wx.showModal({
                              //     title: '',
                              //     content: '请在系统设置中打开定位服务',
                              //     confirmText: '确定',
                              //     success: function (res) {
                              //     }
                              //   })
                              // }
                            },fail(res)
                            {
                              console.log(res)
                            }
                          })
                        }
                      })
                    } else if (msg.cancel) {
                      wx.showToast({
                        title: '授权失败',
                      })
                    }
                  }, fail(msg) {
                    console.log(msg)
                  }
                })
            } else { // 受过权
              wx.getLocation({
                type: 'gcj02',
                success: function (res) {
                  let from = {
                    latitude: res.latitude,
                    longitude: res.longitude
                  }
                  that.setData({
                    from: from
                  }) 
                  wx.showLoading({
                    title: '正在获取数据',
                    mask: true
                  })
                  console.log(courseData.fieldAttend)
                  if(courseData.fieldAttend=='1'){
                    that.getFieldAttend.call(that)
                  }else{
                  that.getDistance.call(that)
                  }
                  wx.hideLoading()
                },fail(res) {
                  wx.getSetting({
                    success: function (res) {
                      if (!res.authSetting['scope.userLocation']) {
                        wx.showModal({
                          title: '',
                          content: '请允许国科考勤获取您的定位',
                          confirmText: '授权',
                          success: function (res) {
                            if (res.confirm) {
                              that.openSettting()
                            } else {
                              console.log('get location fail');
                            }
                          }
                        })
                      } else {
                        //用户已授权，但是获取地理位置失败，提示用户去系统设置中打开定位    
                        wx.showModal({
                          title: '',
                          content: '请在系统设置中打开定位服务',
                          confirmText: '确定',
                          success: function (res) {
                          }
                        })
                      }
                    }, fail(res) {
                      console.log(res)
                    }
                  })
                }
              })
            }
          },fail(res)
          {
            console.log(res)
          }
        })
      })
    },
    openSettting(){
      wx.openSetting()
    },
    // 外勤打卡
    getFieldAttend() {
      let that = this
      let courseData = this.properties.courseData
      let nowTime = that.data.millisecond
      clearTimeout(globalData.timer)
      // 判断一下现在有没有处在打卡区间里
      if (this.data.millisecond < (courseData.todayCalssBegind - courseData.early_punch_card * 60000)) { // 还没到打卡时间不能打
        courseData.classStyle = 'skyblue'
        courseData.text = '外勤打卡'
        courseData.canClock = false
        courseData.lateBool = true
        courseData.bottomText = '未到打卡时间，暂不能打卡'
        that.setData({
          courseData: courseData
        })
        console.log(this.data.courseData)
        return
      }
      if (this.data.millisecond > courseData.todayCalssEnd) {
        courseData.classStyle = 'skyblue'
        courseData.text = '外勤打卡'
        courseData.canClock = false
        courseData.lateBool = true
        courseData.bottomText = '打卡时间已过'
        courseData.truant = true
        that.setData({
          courseData: courseData
        })
        return
      }
      if (nowTime >= (courseData.todayCalssBegind - courseData.early_punch_card * 60000) && nowTime <= courseData.todayCalssBegind) { // 没有迟到 
        courseData.classStyle = 'blue'
        courseData.text = '外勤打卡'
        courseData.canClock = true
        courseData.lateBool = false
        courseData.bottomText = '你已进入考勤范围内'
      }else{
        courseData.classStyle = 'blue'
        courseData.text = '外勤打卡'
        courseData.canClock = true
        courseData.lateBool = false
        courseData.bottomText = '你已进入考勤范围内'
      } 
      // else if (nowTime > courseData.todayCalssBegind && nowTime <= courseData.todayCalssEnd) { //迟到
      //   courseData.classStyle = 'orange'
      //   courseData.text = '迟到打卡'
      //   courseData.canClock = true
      //   courseData.lateBool = true
      //   courseData.bottomText = '你已进入考勤范围内'
      // }
      that.setData({
        courseData: courseData
      })
      wx.getLocation({
        type: 'gcj02',
        success: function (res) {
          if (res) {
            let latitude = res.latitude,
              longitude = res.longitude;
            qqMapSdk.reverseGeocoder({
              location: {
                latitude: latitude,
                longitude: longitude
              },
              success: function (res) {
                that.setData({
                  fieldAddress: res.result.address
                })
                wx.setStorageSync('localAddress', that.data.fieldAddress)
                console.log(that.data.fieldAddress)
              },fail(res) {
                console.log(res)
              }
            })
          }
        },fail(res) {
          console.log(res)
        }
      })
    },

    // 腾讯地图计算2点距离
    getDistance() {
      let that = this
      let courseData = this.properties.courseData
      clearTimeout(globalData.timer)
      // 判断一下现在有没有处在打卡区间里
      if (this.data.millisecond < (courseData.todayCalssBegind - courseData.early_punch_card*60000)) {  // 还没到打卡时间不能打

        courseData.classStyle = 'skyblue'
        courseData.text = '上课打卡'
        courseData.canClock = false
        courseData.lateBool = true
        courseData.bottomText = '未到打卡时间，暂不能打卡'
        that.setData({
          courseData: courseData
        })
        globalData.timer = setTimeout(() => {
          that.getDistance.call(that)
        }, 1000)
        return
      }

      if (this.data.millisecond > courseData.todayCalssEnd) {
        courseData.classStyle = 'skyblue'
        courseData.text = '上课打卡'
        courseData.canClock = false
        courseData.lateBool = true
        courseData.bottomText = '打卡时间已过'
        courseData.truant = true
        that.setData({
          courseData: courseData
        })

        return
      }


      wx.getLocation({
        type: 'gcj02',
        success: function(res) {
          if (res) {
            qqMapSdk.calculateDistance({
              to: [that.data.to],
              from: that.data.from,
              success(res) {
                let nowTime = that.data.millisecond

                // 计算2点距离成功后
                if (res.status == '0') {
                  
                  // 小于 500米可以考勤
                  // console.log('res.result.elements[0].distance * 1 , that.data.distance * 1')
                  console.log(res.result.elements[0].distance * 1 , that.data.distance * 1)
                  if (res.result.elements[0].distance * 1 < that.data.distance * 1) {
                    // 判断一下时间有没有迟到  that.data.distance*1

                    if (nowTime >= (courseData.todayCalssBegind - courseData.early_punch_card*60000) && nowTime <= courseData.todayCalssBegind) { // 没有迟到         
                      
                      courseData.classStyle = 'blue'
                      courseData.text = '上课打卡'
                      courseData.canClock = true
                      courseData.lateBool = false
                      courseData.bottomText = '你已进入考勤范围内'
                    } else if (nowTime > courseData.todayCalssBegind && nowTime <= courseData.todayCalssEnd ){ //迟到
                      courseData.classStyle = 'orange'
                      courseData.text = '迟到打卡'
                      courseData.canClock = true
                      courseData.lateBool = true
                      courseData.bottomText = '你已进入考勤范围内'
                    }
                    // 还没进入考勤
                  } else {
                    courseData.classStyle = 'skyblue'
                    courseData.text = '上课打卡'
                    courseData.canClock = false
                    courseData.lateBool = true
                    courseData.bottomText = '你不在考勤范围内，暂不能打卡'
                  }
                }

                that.setData({
                  courseData: courseData
                })
                globalData.timer = setTimeout(() => {
                  that.getDistance.call(that)
                }, 5000)
              },
              fail(res) {
                console.log(res)
                globalData.timer = setTimeout(() => {
                  that.getDistance.call(that)
                }, 5000)
              }
            })
          }
        },fail(res) {
          console.log(res)
        }
      })

    },

    // 获取现在时间
    getNowTime() {
      let millisecond = this.data.millisecond
      millisecond += 1000
      this.setData({
        millisecond: millisecond,
        nowTime: formatTime(millisecond, 2).split(' ')[1]
      })

      setTimeout(() => {
        this.getNowTime.call(this)
      }, 1000)
    },

    // 打卡点击事件
    clockInBtn() {
      let [courseData, nowTime, status,that] = [this.properties.courseData, this.data.nowTime, null, this]
      if (!courseData.canClock) return // 判断能不能点击
      wx.showLoading({
        title: '打卡中',
      })
      courseData.punch_date = nowTime
      status =!!courseData.lateBool ? 2 : 1
      // 打完卡更新好后台
      upData(courseData.id, new Date(wx.getStorageSync('time').split('-').join('/') + ' ' + courseData.punch_date).getTime(), status).then(res =>{
        log.error('upData',res)
        if (res.code == '0'){
          clearTimeout(globalData.timer)
          courseData.showClockIn = false
          wx.hideLoading()
          // 把现在改变的数据设置到父组件数组里
          // 所有要带到主页面的数据，都装在eventDetail里面
          var eventDetail = {
            childData: courseData,
          }
          // 触发事件的选项 bubbles是否冒泡，composed是否可穿越组件边界，capturePhase 是否有捕获阶段
          var eventOption = {
            composed: true
          }
          that.triggerEvent('getChildData', eventDetail, eventOption)
          that.setData({
            courseData: courseData,
            showResultcourse:true
          })
          getAttendPoster(courseData.id).then(res => {
            log.error('getAttendPoster', res)
            this.setData({
              monthNum: res.number,
              posterData: res.map
            })
            this.createPosterPic()
          })
        } else {
          wx.showLoading({
            title: '打卡失败',
          })
          setTimeout(function () {
            wx.hideLoading()
          }, 1000)
        }
        
      })
    },
    // 生成海报
    createPosterPic() {
      let that = this
      let posterData = that.data.posterData
      let monthNum = that.data.monthNum
      // console.log(that.data.posterBg[that.data.index])
      // console.log(that.data.posterBg[that.data.index].imgUrl)
      let promise1 = new Promise(function (resolve, reject) {
        wx.getImageInfo({
          src: that.data.posterBg[that.data.index].imgUrl,
          success: function (res) {
            console.log(res)
            resolve(res);
          }
        })
      });
      console.log(that.data.posterData.photo)
      let promise2 = new Promise(function (resolve, reject) {
        wx.getImageInfo({
          src: that.data.posterData.photo,
          success: function (res) {
            console.log(res)
            resolve(res);
          }
        })
      });

      let promise3 = new Promise(function (resolve, reject) {
        wx.getImageInfo({
          src: '/images/grade/college.jpg',
          success: function (res) {
            console.log(res)
            resolve(res);
          }
        })
      });

      Promise.all([
        promise1, promise2, promise3
      ]).then(res => {
        console.log(res)
        const ctx = wx.createCanvasContext('clockIn',this)
        //主要就是计算好各个图文的位置
        ctx.drawImage(res[0].path, 0, 0, 337, 482.5)

        ctx.save()
        ctx.beginPath()
        ctx.arc(67.25, 60.75, 19.75, 0, 2 * Math.PI)
        ctx.setStrokeStyle('red')
        ctx.stroke()
        ctx.clip()
        if (res[1].path.indexOf('wxfile') != -1 || res[1].path.indexOf('http') != -1)
        {
          ctx.drawImage(res[1].path, 47.5, 41, 39.5, 39.5)
        }else
        {
          ctx.drawImage('/' + res[1].path, 47.5, 41, 39.5, 39.5)
        }
        ctx.restore()

        ctx.drawImage('/' + res[2].path, 210, 333, 77, 77)

        ctx.setTextAlign('center')
        ctx.setFillStyle('#FF6252')
        ctx.setFontSize(15)
        ctx.fillText(posterData.realName, 127.5, 54.5)
        ctx.fillText('我在国科学院学习', 222.5, 54.5)
        ctx.fillText('《' +posterData.courseName + '》', 177.5, 74.5)


        ctx.setTextAlign('center')
        ctx.setFillStyle('#FF6252')
        ctx.setFontSize(24)
        // 下面这三行是图片中的文字，这些文字也是要通过canvas画上去的
        ctx.fillText(monthNum, 67.5, 352)
        ctx.fillText(posterData.sumNumber, 136.5, 352)
        ctx.fillText(formatTime(posterData.attendDate,1).split(' ')[0], 105, 405)

        ctx.setTextAlign('center')
        ctx.setFillStyle('#666666')
        ctx.setFontSize(10)
        ctx.fillText('本月打卡次数', 67.5, 366.5)
        ctx.fillText('累计打卡次数', 136.5, 366.5)
        ctx.fillText('时间', 105, 424.5)

        ctx.setTextAlign('left')
        ctx.setFillStyle('#FF6252')
        ctx.setFontSize(10)
        ctx.fillText('扫码关注国科学院~', 210, 424.5)
        ctx.stroke()
        ctx.draw()
      })
    },
    toggleDialog() {
      this.setData({
        showResultcourse: !this.data.showResultcourse
      })
    },
    getKnow(){
      this.setData({
        showResultcourse:false
      })
    },
    changeBg() {
      let posterBgLen = this.data.posterBg.length
      if (this.data.index < posterBgLen - 1) {
        this.data.index++
        this.setData({
          showResultcourse: true,
          index: this.data.index
        })
        this.createPosterPic()
      } else {
        this.setData({
          showResultcourse: true,
          index: 0
        })
        this.createPosterPic()
      }
    },
    /**
     * 保存到相册
    */
    save: function () {
      var that = this
      wx.showLoading({
        title: '努力生成中...'
      })
      // 生产环境时 记得这里要加入获取相册授权的代码
      // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.writePhotosAlbum" 这个 scope
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {
                // 用户已经同意小程序相册功能，后续调用 wx.saveImageToPhotosAlbum 接口不会弹窗询问
                wx.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  width: 337,
                  height: 482.5,
                  destWidth: 674,
                  destHeight: 965,
                  canvasId: 'clockIn',
                  success: function (res) {
                    console.log(res.tempFilePath);
                    that.setData({
                      preurl: res.tempFilePath,
                      previewHidden: false,
                    })
                    that.startSaveImage()
                    wx.hideLoading()
                  },
                  fail: function (res) {
                    console.log(res)
                    that.setData({
                      saveErrorDialog: true
                    })
                    setTimeout(() => {
                      that.setData({
                        saveErrorDialog: false
                      })
                    }, 2000)
                  }
                }, that)
              }
            })
          } else {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: 337,
              height: 482.5,
              destWidth: 674,
              destHeight: 965,
              canvasId: 'clockIn',
              success: function (res) {
                console.log(res.tempFilePath);
                that.setData({
                  preurl: res.tempFilePath,
                  previewHidden: false,
                })
                that.startSaveImage()
                wx.hideLoading()
              },
              fail: function (res) {
                console.log(res)
                that.setData({
                  saveErrorDialog: true
                })
                setTimeout(() => {
                  that.setData({
                    saveErrorDialog: false
                  })
                }, 2000)
              }
            },that)
          }
        }
      })

    },

    startSaveImage: function () {
      let that = this;
      console.log(that.data.preurl)
      wx.saveImageToPhotosAlbum({
        filePath: that.data.preurl,
        success(res) {
          that.setData({
            previewHidden: true,
            saveSuccessDialog: true
          })
          setTimeout(() => {
            that.setData({
              saveSuccessDialog: false
            })
          }, 2000)
        },fail()
        {
          that.setData({
            saveErrorDialog: true
          })
          setTimeout(() => {
            that.setData({
              saveErrorDialog: false
            })
          }, 2000)
        }
      })
    }
  }
})